#!/usr/bin/python -S
"""
sync_test.py: Tests for sync.py
"""

__author__ = 'Andy Chu'


import sys
import unittest

import ioloop
import sync  # module under test
import timer


class PoolTest(unittest.TestCase):
  def setUp(self):
    pass

  def tearDown(self):
    pass

  def testPool(self):
    p = sync.Pool()
    p.put(1)
    def echo(item):
      print 'got', item
    p.take(echo)
    p.take(echo)
    p.take(echo)
    p.put(2)
    p.put(3)

    loop = ioloop.IOLoop.instance()
    loop.start()

  def testTimeout(self):
    p = sync.Pool(take_deadline=3.0)
    print '\t\t\tput 1'
    p.put(1)
    def echo(item):
      print '\t\tgot', item

    def on_timeout():
      print '\t\ttimeout'

    print 'taking with timeout'

    p.take(echo, on_timeout)
    p.take(echo, on_timeout)
    # this one will time out
    p.take(echo, on_timeout)

    def put_more():
      print '\t\t\tput 2'
      p.put(2)
    def put_more2():
      print '\t\t\tput 3'
      p.put(3)
      print '\t\t\tput 4'
      p.put(4)
      print '\t\t\tput 5'
      p.put(5)
    def take_more():
      p.take(echo, on_timeout)  # get 4 (3 times out)
      p.take(echo, on_timeout)  # get 5
      p.take(echo, on_timeout)  # another timeout

    print 'putting one element in after 2 seconds'
    timer.set_timeout(2, put_more)
    print 'putting two more elements after 4 seconds'
    timer.set_timeout(4, put_more2)
    print 'taking two elements after 6 seconds'
    timer.set_timeout(4, take_more)

    loop = ioloop.IOLoop.instance()
    loop.start()


if __name__ == '__main__':
  unittest.main()
